<template>
  <div class="admin-section">
    <!-- 头部导航 -->
    <header class="admin-header">
      <div class="admin-header-left">
        <div class="logo">
          <span class="logo-text">3D IDEA - 管理后台</span>
        </div>
      </div>
      <div class="admin-header-right">
        <button class="btn-back" @click="handleBackToHome">
          返回首页
        </button>
      </div>
    </header>
    
    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="filter-tabs">
        <button 
          v-for="tab in filterTabs" 
          :key="tab.key"
          @click="setActiveTab(tab.key)"
          :class="['tab-button', { 'active': activeTab === tab.key }]"
        >
          {{ tab.label }}
        </button>
      </div>
      
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchQuery"
          placeholder="搜索模型名称..."
          class="search-input"
        >
      </div>
    </div>

    <!-- 模型列表 -->
    <div class="models-grid">
      <!-- 新建模型卡片 -->
      <div class="model-card new-card" @click="openUploadModal">
        <div class="new-icon">+</div>
        <div class="new-text">新建</div>
      </div>

      <!-- 模型卡片列表 -->
      <div 
        v-for="model in filteredModels" 
        :key="model.fileUrl"
        class="model-card"
        @click="openPreview(model)"
      >
        <div class="model-preview">
          <img 
            v-if="model.surfacePlot" 
            :src="model.surfacePlot" 
            alt="Cover" 
            class="model-image"
            @error="handleImageError"
          />
          <div v-else class="model-placeholder">
            <div class="placeholder-box">
              <img src="@/assets/3d.svg" alt="3D" class="placeholder-icon" />
            </div>
            <span class="placeholder-text">点击预览3D模型</span>
          </div>
        </div>
        
        <div class="model-info">
          <h3 class="model-name">{{ model.productName }}</h3>
          <p class="model-category">分类: {{ getCategoryName(model.category) }}</p>
          <p class="model-description" v-if="model.description">{{ model.description }}</p>
        </div>
        
        <div class="model-actions">
          <button 
            class="action-btn share-btn" 
            @click.stop="shareModel(model)"
            title="分享"
          >
            <img src="@/assets/sharemodel.svg" alt="分享" class="action-icon" />
          </button>
          <button
            class="action-btn download-btn"
            @click.stop="downloadModel(model)"
            title="下载"
          >
            <img src="@/assets/download.svg" alt="下载" class="action-icon" />
          </button>
          <button 
            class="action-btn edit-btn" 
            @click.stop="editModel(model)"
            title="编辑"
          >
            <img src="@/assets/edit.svg" alt="编辑" class="action-icon" />
          </button>
          <button 
            class="action-btn delete-btn" 
            @click.stop="deleteModel(model)"
            title="删除"
          >
            <img src="@/assets/delete.svg" alt="删除" class="action-icon" />
          </button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="filteredModels.length === 0 && !isLoading" class="empty-state">
      <h3 class="empty-title">暂无模型文件</h3>
      <p class="empty-description">点击"新建"按钮上传您的第一个3D模型</p>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="isLoading" class="empty-state">
      <h3 class="empty-title">加载中...</h3>
    </div>
  </div>
  
  <!-- 3D模型预览模态框 -->
  <ModelPreviewModal
    :visible="showPreviewModal"
    :model="selectedModel"
    @close="closePreviewModal"
  />
  
  <!-- 上传/编辑模态框 -->
  <UploadModal
    :visible="showUploadModal"
    :edit-model="editingModel"
    :categories="allCategories"
    @close="handleCloseUpload"
    @upload-success="handleUploadSuccess"
    @edit-success="handleEditSuccess"
  />
  
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getModelFile, deleteModelData } from '@/api/model'
import { getUserInfo } from '@/utils/auth'
import AESencrypt from '@/utils/AESencrypt'
import ModelPreviewModal from '@/components/ModelPreviewModal.vue'
import UploadModal from '@/components/UploadModal.vue'

// 路由实例
const router = useRouter()

// 筛选和搜索
const activeTab = ref('all')
const searchQuery = ref('')
const isLoading = ref(false)

// 模型数据
const models = ref([])

// 完整的分类列表（用于上传时选择）
const allCategories = [
  '建筑模型',
  '家具模型',
  '交通工具',
  '角色模型',
  '衣物模型',
  '自然景观',
  '电子产品',
  '其他'
]

// 预览相关
const showPreviewModal = ref(false)
const selectedModel = ref(null)

// 上传相关
const showUploadModal = ref(false)

// 编辑相关
const editingModel = ref(null)

onMounted(async () => {
  // 获取用户信息
  const userInfo = getUserInfo()
  
  if (!userInfo) {
    ElMessage.warning('未登录，无法获取模型列表')
    return
  }
  
  // 获取用户名
  const user = AESencrypt.encryptsixteen(
    userInfo.user || userInfo.username || userInfo.phone || ''
  )
  
  if (!user) {
    ElMessage.error('用户信息不完整')
    return
  }
  
  isLoading.value = true
  
  try {
    // 调用API获取模型列表
    const response = await getModelFile(user)
    // 处理返回的数据
    // if (response && response.data) {
    //   models.value = response.data
    // } else if (Array.isArray(response)) {
    //   models.value = response
    // }
    if (Array.isArray(response)) {
      models.value = response
    } else if (response && response.data) {
      models.value = response.data
    }
    
    if (models.value.length > 0) {
      ElMessage.success(`成功加载 ${models.value.length} 个模型`)
    }
  } catch (error) {
    ElMessage.error('获取模型列表失败: ' + (error.message || '未知错误'))
  } finally {
    isLoading.value = false
  }
})
// 计算属性：过滤后的模型列表
const filteredModels = computed(() => {
  let filtered = models.value

  // 按分类筛选
  if (activeTab.value === 'all') {
    // 显示全部，不过滤
  } else {
    // 显示特定分类的模型
    filtered = filtered.filter(model => model.category === activeTab.value)
  }

  // 按搜索关键词筛选
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(model =>
      model.productName.toLowerCase().includes(query) ||
      model.description?.toLowerCase().includes(query)
    )
  }

  return filtered
})

// 从模型数据中提取分类列表
const dynamicCategories = computed(() => {
  // 从模型数据中提取所有唯一的分类
  const categorySet = new Set()
  models.value.forEach(model => {
    if (model.category) {
      categorySet.add(model.category)
    }
  })

  // 返回排序后的分类列表
  return Array.from(categorySet).sort()
})

// 动态生成筛选标签页
const filterTabs = computed(() => {
  const tabs = [
    { key: 'all', label: '全部' }
  ]

  // 添加所有分类标签
  dynamicCategories.value.forEach(category => {
    tabs.push({
      key: category,
      label: category
    })
  })

  return tabs
})

// 方法
const setActiveTab = (tabKey) => {
  activeTab.value = tabKey
}

const getCategoryName = (category) => {
  const categoryMap = {
    'architecture': '建筑模型',
    'furniture': '家具模型',
    'vehicle': '交通工具',
    'character': '角色模型',
    'weapon': '武器模型',
    'nature': '自然景观',
    'electronics': '电子产品',
    'other': '其他'
  }
  return categoryMap[category] || category
}

const openUploadModal = () => {
  showUploadModal.value = true
}

const handleCloseUpload = () => {
  showUploadModal.value = false
  editingModel.value = null
}

const handleUploadSuccess = async () => {
  // 刷新模型列表
  const userInfo = getUserInfo()
  if (!userInfo) return
  
  const user = userInfo.user || userInfo.username || userInfo.phone || ''
  if (!user) return
  
  isLoading.value = true
  try {
    const response = await getModelFile(user)
    if (response && response.data) {
      models.value = response.data
    } else if (Array.isArray(response)) {
      models.value = response
    }
  } catch (error) {
    console.error('刷新模型列表失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 返回首页
const handleBackToHome = () => {
  router.push('/')
}

// 打开预览
const openPreview = (model) => {
  selectedModel.value = model
  showPreviewModal.value = true
}

// 关闭预览
const closePreviewModal = () => {
  showPreviewModal.value = false
  selectedModel.value = null
}

// 模型操作
const shareModel = (model) => {
  // 复制链接到剪贴板
  const shareUrl = model.fileUrl
  navigator.clipboard.writeText(shareUrl).then(() => {
    ElMessage.success('模型链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.info(`模型链接: ${shareUrl}`)
  })
}

// 下载模型
const downloadModel = (model) => {
  // 检查是否有下载链接
  if (!model.fileUrl) {
    ElMessage.warning('下载链接无效')
    return
  }
  
  // 创建临时链接进行下载
  const link = document.createElement('a')
  link.href = model.fileUrl
  // 尝试使用模型名称作为文件名
  link.download = model.productName || 'model'
  link.target = '_blank'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const editModel = (model) => {
  editingModel.value = model
  showUploadModal.value = true
}

const handleEditSuccess = async () => {
  // 刷新模型列表
  const userInfo = getUserInfo()
  if (!userInfo) return
  
  const user = userInfo.user || userInfo.username || userInfo.phone || ''
  if (!user) return
  
  isLoading.value = true
  try {
    const response = await getModelFile(user)
    if (response && response.data) {
      models.value = response.data
    } else if (Array.isArray(response)) {
      models.value = response
    }
  } catch (error) {
    console.error('刷新模型列表失败:', error)
  } finally {
    isLoading.value = false
  }
}

const deleteModel = async (model) => {
  try {
    // 使用Element Plus的确认对话框
    await ElMessageBox.confirm(
      `确定要删除模型 "${model.productName}" 吗？此操作不可撤销。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    // 使用16位密钥加密ID
    const encryptedId = AESencrypt.encryptsixteen(model.id.toString())
    
    // 调用删除API（使用POST请求，避免URL路径问题）
    await deleteModelData(encryptedId)
    
    // 删除成功，从列表中移除该模型
    const index = models.value.findIndex(m => m.id === model.id)
    if (index > -1) {
      models.value.splice(index, 1)
    }
    
    ElMessage.success(`模型 "${model.productName}" 删除成功`)
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除
      return
    }
    
    console.error('删除模型失败:', error)
    ElMessage.error('删除模型失败: ' + (error?.message || '未知错误'))
  }
}

// 处理图片加载错误
const handleImageError = (event) => {
  const img = event.target
  img.style.display = 'none'
}
</script>

<style scoped>
/**
 * 管理区域样式
 */
.admin-section {
  min-height: 100vh;
  background: #f8f9fa;
}

.admin-section > .admin-header {
  position: sticky;
  top: 0;
  z-index: 10;
}

.admin-section > .filter-section {
  max-width: 1200px;
  margin: 0 auto 30px;
}

.admin-section > .models-grid {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px 30px;
}

.admin-section > .empty-state {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 管理后台头部 */
.admin-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  margin-bottom: 30px;
  border-bottom: 1px solid #e5e5e5;
  background: white;
}

.admin-header-left {
  flex: 1;
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo-text {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.admin-header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.btn-back {
  padding: 12px 24px;
  border: 2px solid #28a745;
  background: transparent;
  color: #28a745;
  border-radius: 25px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-back:hover {
  background: #28a745;
  color: white;
}

/* 筛选和搜索 */
.admin-section .filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.filter-tabs {
  display: flex;
  gap: 10px;
}

.tab-button {
  padding: 8px 16px;
  border: 1px solid #e5e5e5;
  background: white;
  color: #666;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.tab-button.active {
  border-color: #3742fa;
  background: #3742fa;
  color: white;
}

.search-box {
  flex: 1;
  max-width: 300px;
}

.search-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #e5e5e5;
  border-radius: 6px;
  font-size: 14px;
  background: white;
}

.search-input:focus {
  outline: none;
  border-color: #3742fa;
  box-shadow: 0 0 0 2px rgba(55, 66, 250, 0.1);
}

/* 模型网格 */
.models-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 16px;
  margin-bottom: 40px;
}

.model-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  transition: all 0.2s;
  cursor: pointer;
  border: 1px solid #e8e8e8;
}

.model-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  border-color: #d0d0d0;
}

.new-card {
  border: 2px dashed #d0d0d0;
  background: #fafafa;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 160px;
  cursor: pointer;
  transition: all 0.2s;
}

.new-card:hover {
  background: #f0f0f0;
  border-color: #b0b0b0;
}

.new-icon {
  font-size: 36px;
  font-weight: bold;
  color: #666;
  margin-bottom: 8px;
}

.new-text {
  font-size: 14px;
  font-weight: 500;
  color: #666;
}

.model-preview {
  position: relative;
  height: 160px;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.model-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.model-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  height: 100%;
  background: #f8f8f8;
  color: #666;
  transition: all 0.2s;
}

.model-card:hover .model-placeholder {
  background: #f0f0f0;
}

.placeholder-box {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 4px;
}

.placeholder-icon {
  width: 40px;
  height: 40px;
  opacity: 0.4;
  filter: brightness(0.6);
}

.placeholder-text {
  font-size: 12px;
  color: #999;
  font-weight: 400;
}

.processing-indicator {
  position: absolute;
  bottom: 10px;
  right: 10px;
  width: 32px;
  height: 32px;
  background: #3742fa;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.model-info {
  padding: 12px;
}

.model-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin: 0 0 6px 0;
}

.model-category {
  font-size: 12px;
  color: #999;
  margin: 0 0 4px 0;
}

.model-description {
  font-size: 12px;
  color: #999;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.model-actions {
  display: flex;
  justify-content: flex-end;
  gap: 6px;
  padding: 0 12px 12px;
}

.action-btn {
  width: 28px;
  height: 28px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}

.action-icon {
  width: 16px;
  height: 16px;
  opacity: 0.7;
  transition: opacity 0.2s;
}

.action-btn:hover .action-icon {
  opacity: 1;
}

.share-btn {
  background: #f0f0f0;
}

.share-btn:hover {
  background: #e3f2fd;
}

.edit-btn {
  background: #f0f0f0;
}

.edit-btn:hover {
  background: #f5f5f5;
}

.delete-btn {
  background: #f0f0f0;
}

.delete-btn:hover {
  background: #fff5f5;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0 0 10px 0;
}

.empty-description {
  font-size: 14px;
  color: #666;
  margin: 0;
}



/* 响应式设计 */
@media (max-width: 768px) {
  .filter-section {
    flex-direction: column;
    gap: 15px;
  }
  
  .models-grid {
    grid-template-columns: 1fr;
    gap: 15px;
  }
}
</style>
